import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import other from '@renderer/utils/other';
import '@renderer/theme/index.scss';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
import { createMittBus } from './utils/mitt'
import { createPiniaInstance } from './stores';
import { createRouterInstance } from './router';
import { createI18nInstance } from './i18n';

const setupIsolatedCssVariable = (mountPoint: HTMLElement, nodeId: string) => {
  if (!mountPoint || import.meta.env.DEV) return null;

  // 生成节点专属的CSS变量名（关键：通过nodeId隔离）
  const cssVarName = `--mount-point-height-${nodeId}`;
  
  // 更新当前节点的CSS变量
  const updateCssVariable = () => {
    const height = mountPoint.offsetHeight;
    // 只设置当前节点容器的样式（非全局document）
    mountPoint.style.setProperty(cssVarName, `${height}px`);
    return height;
  };

  // 初始化变量
  updateCssVariable();

  // 监听当前节点的尺寸变化（仅影响自身）
  const resizeObserver = new ResizeObserver(() => {
    updateCssVariable();
  });
  resizeObserver.observe(mountPoint);

  // 清理函数：仅移除当前节点的变量和监听
  return () => {
    resizeObserver.unobserve(mountPoint);
    mountPoint.style.removeProperty(cssVarName);
  };
};

if (import.meta.env.DEV) {
  // 开发环境：使用100vh作为默认值
  document.documentElement.style.setProperty('--mount-point-height-11111', '1000px');
  // 原有开发环境逻辑...
  const app = createApp(App)
  const mittbus = createMittBus();
  const pinia = createPiniaInstance();
  const router = createRouterInstance(pinia)
  const i18n = createI18nInstance(pinia)
  app.use(pinia)
     .use(i18n)
     .use(ElementPlus)
     .use(router)
  
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  
  other.elSvg(app);
  app.config.globalProperties.$eventBus = window.marvelousEventBus;
  app.config.globalProperties.$nodeInfo = { isDev: true };
  app.config.globalProperties.$mittBus = mittbus;
  app.config.globalProperties.$cssVarName = '--mount-point-height-11111';
  const MarvelousVueBridge = {
    install(app) {
      window.__MARVELOUS_VUE_APP__ = {
        isDev: true,
        logEnv: () => console.log('开发环境模式')
      };
    }
  };
  app.use(MarvelousVueBridge);
  app.mount('#app');
} else {
  window.mountMarvelousVueApp = function(mountPoint, options) {
    if (!mountPoint) {
      console.error('Vue挂载点元素未提供');
      return null;
    }
    if (!options?.nodeId) {
      console.error('挂载失败：无效的nodeId参数', {
        received: options?.nodeId,
        expected: '非空字符串'
      });
      return null;
    }
    const { nodeId } = options;
    const cleanupCssVariable = setupIsolatedCssVariable(mountPoint,nodeId);
    const mittbus = createMittBus();
    const app = createApp(App)
    const pinia = createPiniaInstance();
    const router = createRouterInstance(pinia,nodeId)
    const i18n = createI18nInstance(pinia)
    app.use(pinia)
       .use(i18n)
       .use(ElementPlus)
       .use(router)
    app.directive('stop-comfy-events', {
      mounted(el) {
        const handleKeydown = (e) => { e.stopPropagation(); };
        el.addEventListener('keydown', handleKeydown);
        return () => { el.removeEventListener('keydown', handleKeydown); };
      }
    });
    
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      app.component(key, component)
    }
    
    other.elSvg(app);
    app.config.globalProperties.$eventBus = window.marvelousEventBus;
    app.config.globalProperties.$electronAPI = window;
    app.config.globalProperties.$nodeInfo = options;
    app.config.globalProperties.$mittBus = mittbus;
    app.config.globalProperties.$cssVarName = `--mount-point-height-${nodeId}`;
    const MarvelousVueBridge = {
      install(app) {
        window.__MARVELOUS_VUE_APP__ = {
          mountPoint,
          getMountPointHeight: () => mountPoint.offsetHeight,
          stopHeightMonitor: cleanupCssVariable
        };
      }
    };
    app.use(MarvelousVueBridge);
    app.mount(mountPoint);
    const cleanup = () => {
        cleanupCssVariable?.();
        app.unmount();
        router.clearRoutes();
        console.log("清理节点资源完成")
    };
    return {
        instance: app, 
        cleanup: cleanup
    };
  };
}